#include "MultiScoringScheme.h"

using namespace Biopool;


MultiScoringScheme::MultiScoringScheme(SubMatrix *sub, AlignmentData *ad, Structure *str, vector< vector<Biopool::Align*> > ali, UpgmaCluster* u, vector<string> seq) :
									ScoringScheme(sub, ad, str), alignments(ali), uc(u), sequences(seq)
{

}


MultiScoringScheme::~MultiScoringScheme()
{

}


double MultiScoringScheme::scoring(int pos1, int pos2){
	double score = 0;
	int n = uc->left->sequences.size();
	int m = uc->right->sequences.size();
	


	for(int i = 0; i < n; i++){ //scans left sequences
		
		for(int j = 0; j < m; j++){ //scans right sequences
			char amino1 =alignments[uc->left->sequences[i]][uc->right->sequences[j]]->getMatch()[0][pos1];
			char amino2 =alignments[uc->left->sequences[i]][uc->right->sequences[j]]->getMatch()[1][pos2];

			if(amino1 == '-' || amino2 == '-'){ //we must take into account that there may be gaps already in the alignment
				if(amino1 == amino2)
					score += 0.5; //half a point for gap against gap
				else
					score += -1.5; //minus 1.5 points for gap against aminoacid
			}
			else{
				//otherwise we calculate the score using the normal seuqence2sequence alignment
				int posRes1 = 0, posRes2 = 0;
				string residues = sub->getResidues();
				for(int k = 0; k < residues.size(); k++){
					if(residues[k] == amino1)
						posRes1 = k;
					if(residues[k] == amino2)
						posRes2 = k;
				}
				score += sub->score[posRes1][posRes2];
				//ScoringScheme* tempss = alignments[uc->left->sequences[i]][uc->right->sequences[j]]->getScoringScheme();
				//score += ss->scoring(pos1, pos2);
			}
		}
	}

	return 1.0/(double)(n+m) * score;
}

ScoringScheme* MultiScoringScheme::newCopy(){
	ScoringScheme* ss = new MultiScoringScheme(sub, ad, str, alignments, uc, sequences);
	return ss;
}
